package cn.hengzhu.main_manager.utils.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSONObject;

import cn.hengzhu.main_manager.utils.HttpClientUtil;
import cn.hengzhu.main_manager.utils.config.gzh.WeiXinConst;


@WebFilter("/weixin/open/*") // 所有地址都能拦截
public class WeixinAuthFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}


	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hRequest = (HttpServletRequest) request;
        HttpServletResponse hResponse = (HttpServletResponse) response;
        //如果session中已经存在微信号了，就不用获取了，否则要获取，获取到以后要存放sesion
        String fromUserName = (String) hRequest.getSession().getAttribute("fromUserName");
        if (fromUserName == null)
        {
        	  //只有在微信端才做里面的操作
        	String agent = hRequest.getHeader("User-Agent");
            if (agent != null && agent.toLowerCase().indexOf("micromessenger") >= 0)
            {
                String code = request.getParameter("code");
                String state = request.getParameter("state");
                //如果code不为空，scope为base,scope为userInfo代表用户已经同意,只需发送openid的请求来获取openid
                if (code != null && state != null && state.equals("1"))
                {
                    // 通过Code获取openid来进行授权
                    String url =  WeiXinConst.AUTH_GET_OID
                    		.replace("APPID", WeiXinConst.APPID)
                    		.replace("SECRET", WeiXinConst.APPSECRET)
                    		.replace("CODE", code);
                    String json = HttpClientUtil.httpGet(url);
                    String openid = JSONObject.parseObject(json).getString("openid");
                    hRequest.getSession().setAttribute("fromUserName", openid);
                }
                else
                {
                	  //发送用户同意的请求
                    String path = hRequest.getRequestURL().toString();
                    String query = hRequest.getQueryString();
                    if (query != null)
                    {
                        path = path + "?" + query;
                    }
                    String uri = WeiXinConst.AUTH_URL
                    		.replace("APPID", WeiXinConst.APPID)
                    		.replace("REDIRECT_URI", URLEncoder.encode(path, "UTF-8"))
                            .replace("SCOPE", "snsapi_userinfo")
                            .replace("STATE", "1");
                    hResponse.sendRedirect(uri);
                    return;
                }
            }
        }
        chain.doFilter(hRequest, hResponse);
    }

	@Override
	public void destroy() {

	}

}
